from flask import Flask, render_template, request, jsonify, send_from_directory
import os
from werkzeug.utils import secure_filename
from moviepy.editor import VideoFileClip
import json
from pathlib import Path

app = Flask(__name__)

# 配置
app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024  # 500MB 最大文件大小
app.config['UPLOAD_FOLDER'] = 'static/uploads'

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 允许的视频文件扩展名
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def format_time(seconds):
    """将秒数转换为时:分:秒格式"""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    return f"{hours:02d}:{minutes:02d}:{secs:02d}"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    try:
        if 'video' not in request.files:
            return jsonify({'error': '没有选择文件'}), 400
        
        file = request.files['video']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            
            return jsonify({
                'success': True,
                'filename': filename,
                'filepath': filepath
            })
        else:
            return jsonify({'error': '不支持的文件格式'}), 400
            
    except Exception as e:
        return jsonify({'error': f'上传失败: {str(e)}'}), 500

@app.route('/video-info', methods=['POST'])
def get_video_info():
    try:
        data = request.get_json()
        filename = data.get('filename')
        
        if not filename:
            return jsonify({'error': '文件名不能为空'}), 400
        
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        if not os.path.exists(filepath):
            return jsonify({'error': '文件不存在'}), 404
        
        # 使用MoviePy获取视频信息
        with VideoFileClip(filepath) as video:
            duration = video.duration
            fps = video.fps
            size = video.size
            
        return jsonify({
            'success': True,
            'duration': duration,
            'duration_formatted': format_time(duration),
            'fps': fps,
            'width': size[0],
            'height': size[1],
            'size': f"{size[0]}x{size[1]}"
        })
        
    except Exception as e:
        return jsonify({'error': f'获取视频信息失败: {str(e)}'}), 500

@app.route('/split', methods=['POST'])
def split_video():
    try:
        data = request.get_json()
        filename = data.get('filename')
        start_time = float(data.get('start_time', 0))
        end_time = float(data.get('end_time', 0))
        
        if not filename:
            return jsonify({'error': '文件名不能为空'}), 400
        
        if start_time >= end_time:
            return jsonify({'error': '开始时间必须小于结束时间'}), 400
        
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        if not os.path.exists(filepath):
            return jsonify({'error': '文件不存在'}), 404
        
        # 生成输出文件名
        name, ext = os.path.splitext(filename)
        output_filename = f"{name}_切分_{format_time(start_time).replace(':', '-')}_到_{format_time(end_time).replace(':', '-')}{ext}"
        output_path = os.path.join(app.config['UPLOAD_FOLDER'], output_filename)
        
        # 使用MoviePy切分视频
        with VideoFileClip(filepath) as video:
            # 检查时间范围是否有效
            if end_time > video.duration:
                return jsonify({'error': f'结束时间超出视频长度 ({format_time(video.duration)})'}), 400
            
            # 切分视频
            subclip = video.subclip(start_time, end_time)
            subclip.write_videofile(output_path, verbose=False, logger=None)
            subclip.close()
        
        return jsonify({
            'success': True,
            'output_filename': output_filename,
            'output_path': output_path,
            'message': f'视频切分成功！保存为: {output_filename}'
        })
        
    except Exception as e:
        return jsonify({'error': f'视频切分失败: {str(e)}'}), 500

@app.route('/download/<filename>')
def download_file(filename):
    try:
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
    except Exception as e:
        return jsonify({'error': f'下载失败: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)